import request from './request'
import localStorageApi from './localStorageApi'
import defer from './defer'
// 用户信息配置项
const client_id = '7zfT4aalIg6xkR3FLzk8wE'
const client_secret = '2PCZsgoNbDIr8jX5lJaXOA'
const accessTokenExpires = 0.8 * 3600 * 1000
const cache = {} // 存储对应ajax状态和回调事件流
function deferLodash(func, ...args) {
  if (typeof func !== 'function') {
    throw new TypeError('Expected a function')
  }
  return setTimeout(func, 1, ...args)
}
const Util = {
  // getToken or refreshToken
  getToken({ key = 'getToken', skip = false, refreshToken = '' } = {}) {
    let methodName = `_${key}`
    if (skip === true) {
      return Util[methodName](refreshToken)
    }
    if (!cache[key]) {
      cache[key] = {
        status: 'init',
        callbacks: [],
        resolveData: null
      }
    }
    let deferred = defer() // promise

    switch (cache[key]['status']) {
      case 'reject':
      case 'init':
        cache[key]['status'] = 'pending'
        Util[methodName](refreshToken)
          .then(data => {
            cache[key]['status'] = 'resolve'
            cache[key]['resolveData'] = data
            let current
            // 替换同步产生的错误resolve
            while ((current = cache[key]['callbacks'].pop())) {
              current[0](data)
            }
          })
          .catch(err => {
            cache[key]['status'] = 'reject'
            let current
            // 替换同步产生的错误reject
            while ((current = cache[key]['callbacks'].pop())) {
              current[1](err)
            }
          })
      case 'pending':
        cache[key].callbacks.push([
          function(data) {
            deferred.resolve(data)
          },
          function(err) {
            deferred.reject(err)
          }
        ])
        break
      case 'resolve':
        deferLodash(deferred.resolve, cache[key].resolveData)
    }
    return deferred.promise // promise
  },
  // getToken
  _getToken() {
    return request({
      method: 'get',
      url: `/oauth/oauth2/token?grant_type=client_credentials&client_id=${client_id}&client_secret=${client_secret}`
    })()
  },
  // refreshToken
  _refreshToken(refreshToken) {
    return request({
      method: 'get',
      url: `/oauth/oauth2/token?grant_type=refresh_token&refresh_token=${refreshToken}&client_id=${client_id}&client_secret=${client_secret}`
    })()
  }
}

const setStroge = ({ access_token, refresh_token }) => {
  const nowTime = +new Date()
  localStorageApi.set(
    'access_token',
    access_token,
    nowTime + accessTokenExpires
  )
  localStorageApi.set('refresh_token', refresh_token, nowTime + 6 * 3600 * 1000)
}

const tokenAjax = () => {
  const accessToken = localStorageApi.get('access_token')
  const refreshToken = localStorageApi.get('refresh_token')

  if (accessToken) {
    // 1.存在没有过期
    return Promise.resolve(false)
  } else if (refreshToken) {
    // 2.accessToken过期,refreshToken未过期,refresh
    return Util.getToken({
      key: 'refreshToken',
      refreshToken
    })
  } else {
    // 3.都过期或者压根不存在,getIt
    return Util.getToken()
  }
}

export { tokenAjax, setStroge }
